<?php
namespace app\index\controller;
use think\Db;
use think\Cache;
use think\Controller;
use app\api\controller\Index;

class AdminController extends BaseController
{	
	protected function _initialize() {
	   $type=get_brower_type();
	   $this->assign('browder_type',$type);
       parent::_initialize();
    }
	
	//管理员中心
    public function index()
    {    	
    	$info_user = session('ADMIN');
    	$type = get_brower_type();//判断是微信还是支付宝打开
		$myfriends = db("member")->count();
		$this->assign("counts",$myfriends);
		
		//系统管理员
		$userinfo = db("user")->where("id",$info_user['id'])->find();
    	$this->assign('info_user',$userinfo);
		session('user_info',$userinfo);
		
		//红包记录
		$hb_list = db("hb_list")->sum('balance');
    	$this->assign('hbsum',$hb_list);
		
		//统计会员和合伙人
		$usercount = db("member")->where("is_pt",'<>',1)->count();
    	$this->assign('usercount',$usercount);

		$hhrcount = db("member")->where("is_pt",2)->count();
    	$this->assign('hhrcount',$hhrcount);
       	return  $this->fetch();
    }
	
	 /**
     * 推广配置
     */
    public function config() {
		if ($this->request->isPost()) {
            $ticket_config   = $this->request->post('ticket_config/a');
            $data['value'] = serialize($ticket_config);
            if (Db::name('system')->where('name', 'ticket_config')->update($data) !== false) {
                Cache::set('ticket_config', $ticket_config);
                $this->success('提交成功');
            } else {
                $this->error('提交失败');
            }
        }else{
        	if (Cache::has('')) {
	            $ticket_config = Cache::get('ticket_config');
	        } else {
	            $ticket_config = Db::name('system')->field('value')->where('name', 'ticket_config')->find();
	            $ticket_config = unserialize($ticket_config['value']);
	        }
        	return $this->fetch('config', ['ticket_config' => $ticket_config]);
        }
    }

	//会员列表
    public function member_list()
    {    	
		if($_POST){
			$page = 1;
			if(input("page")){
				$page = input("page");
			}
			$begin = ($page-1)*10;
			$member = db('member')->where('is_pt',2)->order('add_time desc')->limit($begin,10)->select();
			if($member){
				return json(['code'=>200,"list"=>$member]);
			}else{
				return json(['list'=>null]);
			}
		}
		return $this->fetch();
    }
	
	//合伙人列表
    public function pt_list()
    {    	
		if($_POST){
			$tjcount = db('member')->field('pt_id,count(id) as count')->group('pt_id')->buildSql();
			
			$page = 1;
			if(input("page")){
				$page = input("page");
			}
			$begin = ($page-1)*10;
			$ptlist = db('member')->alias('a')
			->join($tjcount." b","a.id=b.pt_id",'LEFT')
			->field('a.*,b.count')
			->where('a.is_pt',1)->order('a.add_time desc')->limit($begin,10)->select();
			if($ptlist){
				return json(['code'=>200,"list"=>$ptlist]);
			}else{
				return json(['list'=>null]);
			}
		}
		return $this->fetch();
    }
	
	//合伙人申请列表
    public function ptsh_list()
    {    	
		if($_POST){
			$page = 1;
			if(input("page")){
				$page = input("page");
			}
			$begin = ($page-1)*10;
			$ptlist = db('member')->where('is_pt',3)->order('add_time desc')->limit($begin,10)->select();
			if($ptlist){
				return json(['code'=>200,"list"=>$ptlist]);
			}else{
				return json(['list'=>null]);
			}
		}
		return $this->fetch();
    }
	
	//合伙人审核
	public function shenghe() {
    	if($_POST){
    		if(input("status")==2){
    			$sq=db("pt_sq")->where('id',input('id'))->find();
				$user=db("member")->where("id",$sq['user_id'])->find();
				$old_pt=$user['pt_id'];
				Db::startTrans();
				$result=true;
				$this->update_pt($user['id'],$user['id']);
				$config =get_config('ticket_config');
				$sn=order_create_no();
				//下级会员成为合伙人一次性奖励红包
				if($old_pt){
					gdyj_record_log($old_pt,$config['pt_one'],"推荐会员成为合伙人奖励合伙人",9,$sn,$user['pt_id'],$user['city_id'],$user['id']);
					$sql="update cz_member set total_yj= total_yj + ".$config['pt_one'].",yj=yj+".$config['pt_one']." where id=".$old_pt ;
					$res=Db::execute($sql);
					if(!$res){
						$result=false;
					}
				}
					gdyj_record_log($user['city_id'],$config['ct_one'],"推荐会员成为合伙人奖励运营中心",19,$sn,$user['pt_id'],$user['city_id'],$user['id']);
					$sql="update cz_member set total_yj= total_yj + ".$config['ct_one'].",yj=yj+".$config['ct_one']." where id=".$user['city_id'] ;
					$res=Db::execute($sql);
					if(!$res){
						$result=false;
					}
					$parm['is_pt'] = 1; 
					$parm['pt_id']= $user['id'];
					$res = db('member')->where('id',$user['id'])->update($parm);
					if(!$res){
							$result=false;
					}
					$res = db('pt_sq')->where('id',input('id'))->update(['status'=>2,'sh_time'=>now_time()]);
					if(!$res){
							$result=false;
					}
					$dt['pay_type']=1;
					$dt['order_type']=7;
					$dt['user_id']=$sq['user_id'];
					$dt['balance']=$config['p_balance'];
					$dt['sn']=order_create_no();
					$dt['state']=2;
					$dt['add_time']=now_time();
					$dt['pay_time']=now_time();
					$dt['pt_id']=$user['pt_id'];
					$dt['pt_yj']=$config['pt_one'];
					$dt['city_id']=$user['city_id'];
					$dt['city_yj']=$config['ct_one'];
					$res=db('paylog')->insert($dt);
					
			        if($result){
			        	Db::commit();
//			        	$this->send_mess($user['open_id'],$user['mobile']);
						return json(['code'=>200,'msg'=>'操作成功']);
			        }else{
			        	Db::rollback();
			       		return json(['code'=>402,'msg'=>'操作失败']);
			        }
    		}else{
    				$result = db('pt_sq')->where('id',input('id'))->update(['status'=>3,'sh_time'=>now_time()]);
					
			        if($result){
						return json(['code'=>200,'msg'=>'操作成功']);
			        }else{
			       		return json(['code'=>402,'msg'=>'操作失败']);
			        }
    		}
			
        }
	}
	public function send_mess($openid,$mobile){
			$data=array(
			 	"first" => array(
	                "value"=>'合伙人审核通过通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>$mobile,
	               	"color"=>"#173177"
				   ),
				"keyword2"=>array(
					"value"=>now_time(),
					"color"=>"#173177"
				),
				
	            "remark"=> array(
	                "value"=>'恭喜您,您的合伙人审核已经通过了',
	                "color"=>"#173177"
	            ),
			 );
	    	sendMessage($openid,config("tz2"),$data,config('DOMAIN')."index/member");	
	}

	//跟新下级会员合伙人id
	public function update_pt($user_id,$pt_id){
		$users=db("member")->where("pid1",$user_id)->field("id,pt_id")->select();
		foreach($users as $v){
			db('member')->where('id',$v['id'])->update(['pt_id'=>$pt_id]);
			$res=db("member")->where("pid1",$v['id'])->field("id,pid1")->find();
			if($res){
				$this->update_pt($v['id'],$pt_id);
			}
		}
		
	}

	
	//红包列表
    public function hongb_list()
    {    	
		if($_POST){
			$page = 1;
			if(input("page")){
				$page = input("page");
			}
			$begin = ($page-1)*10;
			$list = db('hb_list')->order('add_time desc')->limit($begin,10)->select();
			if($list){
				return json(['code'=>200,"list"=>$list]);
			}else{
				return json(['list'=>null]);
			}
		}
		return $this->fetch();
    }
	
	//支付列表
    public function paylog_list()
    {    	
		if($_POST){
			$page = 1;
			if(input("page")){
				$page = input("page");
			}
			$begin = ($page-1)*10;
			$list = db('paylog')->order('add_time desc')->limit($begin,10)->select();
			if($list){
				return json(['code'=>200,"list"=>$list]);
			}else{
				return json(['list'=>null]);
			}
		}
		return $this->fetch();
    }
	
	//修改密码
	public function update_pwd(){
		if($_POST){
			$info_user = session('user_info');
			$where['id'] = $info_user['id'];
			$where['login_pwd'] = md5_salt(input("pwd"));
			$update['login_pwd'] = md5_salt(input("pwd1"));
    		$res = db('user')->where($where)->update($update);			
			if($res){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>400,'msg'=>'修改失败']);
			}
		}else{
			return  $this->fetch();
		}
	}
	
		//报表统计
    public function report()
    {
    	$agent_id=session('agent_id');
		$type=input("type")?input("type"):1;
		if($type==2){//按周
			$wheret="week";
			$time=date("Y-m-d",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
			$time.="到".date('Y-m-d',time());
		}else if($type==3){//按月
			$time=date("Y-m-d",mktime(0, 0 , 0,date("m"),1,date("Y")));
			$time.="到".date('Y-m-d',time());
			$wheret="month";
		}else{//按日
			$time=date('Y-m-d',time());
			$wheret="today";
		}
		$where['state']=2;
		$field="count(id) as ids,sum(balance) as balance";
		$res=db("paylog")->field($field)->where($where)->whereTime("add_time",$wheret)->find();
		if(!$res){
			$res['ids']=0;
			$res['balance']=0;
		}
		$hb=db('hb_list')->field($field)->whereTime("add_time",$wheret)->find();
		if(!$hb){
			$hb['ids']=0;
			$hb['balance']=0;
		}
		$this->assign("hb",$hb);
		$this->assign("res",$res);
		$this->assign("type",$type);
		$this->assign("time",$time);
		return $this->fetch();    	
    }
	
	//自定义分享设置
	function share_config(){
		return share_config();
	}
	function glj_sysm(){
		return $this->fetch();
	}
	public function card(){
		$user=session("info_user");
		if(!$user['no']){
			$card=get_user_no($user['id']);
			$user['no']=$card;
			session("info_user")['no']=$card;
			db("info_user")->where("id",$user['id'])->update(["no"=>$card]);
			$user=db('info_user')->where("id",$user['id'])->find();
			session('info_user',$user);
		}
		return $this->fetch();
	}

	public function share_erweim(){
		$info_user = session('info_user');
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	if($info_user['is_fx']!=1){
    		$this->redirect('index/member/open_fx?cz_type=3');
    	}
		//二维码链接
    	$code_url="https://".$_SERVER['HTTP_HOST']."/index/index/regist?fromuid=".session('info_user')['id'];
		$this->assign('logo',session('info_user')['logo']);
		$this->assign('code_url',$code_url);
		return  $this->fetch();
	}
	//我的推荐列表
	public function tj_list(){
		if($_POST){
			$info_user = session('user_info');
			$page=1;
			$where['user_id']=$info_user['id'];
			if(input("page")){
				$page=input("page");
			}
			$begin=($page-1)*10;
			$member = db('member')->where("level",$info_user['id'])->order('add_time desc')->limit($begin,10)->select();
			if($member){
				return json(['code'=>200,"list"=>$member]);
			}else{
				return json(['list'=>null]);
			}
		}
		return $this->fetch();
	}
	//消息中心
	public function msg_list(){
		if($_POST){
			$info_user = session('user_info');
			$page=1;
			$where['user_id']=$info_user['id'];
			if(input("page")){
				$page=input("page");
			}
			$begin=($page-1)*10;
			$member = db('message')->where("user_id",$info_user['id'])->order('add_time desc')->limit($begin,10)->select();
			if($member){
				return json(['code'=>200,"list"=>$member]);
			}else{
				return json(['list'=>null]);
			}
		}
		return $this->fetch();
	}
	//红包记录
	public function hb_list(){
		if($_POST){
			$info_user = session('user_info');
			$page=1;
			$where['user_id']=$info_user['id'];
			if(input("page")){
				$page=input("page");
			}
			$begin=($page-1)*10;
			$logs=db('hb_list')->where("user_id",$info_user['id'])->order('add_time desc')->limit($begin,10)->select();
			if($logs){
				return json(['code'=>200,"list"=>$logs]);
			}else{
				return json(['list'=>null]);
			}
		}
		return $this->fetch();
	}
	public function yindao(){
		return $this->fetch();
	}
	//获取token
	public function getToken($we_config){
		$cache = cache('access_token');
		if ($cache && $cache['token'] && $cache['expire'] > time()) {
			return $cache['token'];
		}
		/*$appid=$we_config['wxpay_appid'];
		$appsecret=$we_config['wxpay_appsercet'];*/
		$appid=config('wxpay_appid');
		$appsecret=config('wxpay_appsercet');
		$rurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
		$weixin =  file_get_contents($rurl);
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		if($array['access_token']){
			$record = array();
			$record['token'] = $array['access_token'];
			$record['expire'] = time() + 7000;
			cache('access_token', $record, $record['expire']);
			return $array['access_token'];
		}else{
			return json(['code'=>406,'msg'=>'获取微信公众号授权失败！错误代码:'.$array['errcode']]);
		}		
	}

	public function about(){
			return  $this->fetch();
	}
	
	//我的推广会员
    public function tglist(){
    	$info_user = session('info_user');
    	$list=db('info_user')->where('level',$info_user['id'])->field("id,user_name,mobile,score")->order('add_time desc')->select();
		$this->assign('list',$list);
       	return  $this->fetch();
    }
    //会员资料
    public function member()
    {
    	$info_user = session('info_user');
    	
    	if(request()->isPost()){
    		$param=input('post.');
    		$user_model = new UserModel();
    		$param['add_time']	= now_time();
    		$rest=$user_model->where('id',$info_user['id'])->update($param);
    		if($rest){
    			$this->success('修改成功');
			}else{
				$this->error('修改失败');
			}
    	}
    	
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	
    	$this->assign('info_user',$info_user);
       	return  $this->fetch();
    }
    //积分记录
    public function score_record()
    {
    	$where['u_id'] 	=  session('info_user')['id'];
    	$loglist = db('log_user_score')->where($where)->order("add_time desc")->paginate(20);
    	$this->assign('loglist',$loglist);
    	$this->assign('empty','<span class="empty">没有数据</span>');
        return  $this->fetch();
    }
    
    //推广中心
    public function friends()
    {	
    	$info_user = session('user_info');
		$myfriends=db("member")->where("pid1",$info_user['id'])->count();
		$this->assign("counts",$myfriends);
    	//二维码链接
    	$redirect_url="https://".$_SERVER['HTTP_HOST']."/index/index/regist?fromuid=".$info_user['id'];
		$info_user['code_url'] = $redirect_url;
		$this->assign('info_user',$info_user);
       	return  $this->fetch();
    }
    //分享赚钱
    public function share_money()
    {
    	$user_info = session('info_user');
    	//获取当前用户信息
		$user_info = db('info_user')->where('id',$user_info['id'])->find();    	
    	$this->assign('user_info',$user_info);
       	return  $this->fetch();
    }
    
    function open_fx(){
    	$info_user = session('info_user');
		$cz_type=2;
		if(input("cz_type")){
			$cz_type=input("cz_type");
		}
		$this->assign('cz_type',$cz_type);
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	$this->assign('info_user',$info_user);
		
		return  $this->fetch();	
    }
    //暂无数据
    function none_style(){
    	return  $this->fetch();	
    }
	public function get_trades(){
		$data=db('sys_platform_type')->where('pid',input("trade_id"))->select();
		return json(["data"=>$data]);
	}
	
	/**
	 * 登录验证
	 * @return string
	 */
	public function login() {
		if(request()->isPost()){
			$where['login_name'] = input('login_name');
			$where['login_pwd'] = md5_salt(input('login_pwd'));
			$user = db('user')->where($where)->find();
			if (!empty($user)) {
				if ($user['status'] != 1) {
					return json(['code'=>408,"msg"=>'当前用户已禁用']);
				} else {
					session('ADMIN', $user);
					db('user')->update(array(
						'last_login_time' => time(),
						'last_login_ip' => $this->request->ip(),
						'id' => $user['id'],
						'session_id' => session_id() //更改登录状态
					));
					return json(['code'=>200,"msg"=>'登录成功']);
				}
			} else {
				return json(['code'=>408,"msg"=>'用户名或密码错误']);
			}
		}
		
		return  $this->fetch();	
	}
}
